/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.activity.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.activity.domain.Activity;
import com.fzhucc.modules.activity.domain.ActivityUsers;
import com.fzhucc.modules.activity.domain.dto.*;
import com.fzhucc.modules.activity.repository.ActivityRepository;
import com.fzhucc.modules.activity.repository.ActivityUsersRepository;
import com.fzhucc.modules.activity.service.mapstruct.ActivityUsersMapper;
import com.fzhucc.modules.appletBanner.domain.dto.AppletBannerQueryCriteria;
import com.fzhucc.modules.sms.SmsService;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.service.DictDetailService;
import com.fzhucc.modules.system.service.DictService;
import com.fzhucc.modules.system.service.UserService;
import com.fzhucc.modules.system.service.dto.DictDetailDto;
import com.fzhucc.modules.system.service.dto.DictDto;
import com.fzhucc.modules.system.service.dto.DictQueryCriteria;
import com.fzhucc.modules.system.service.dto.UserDto;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

import static com.fzhucc.modules.activity.domain.ActivityUsers.AUDIT_STATUS_BE_REVIEWED;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2022-11-17
 **/
@Service
@RequiredArgsConstructor
public class ActivityUsersService {

    private final ActivityUsersRepository activityUsersRepository;
    private final ActivityUsersMapper activityUsersMapper;

    private final ActivityRepository activityRepository;

    private final DictService dictService;

    private final DictDetailService dictDetailService;

    private final UserService userService;

    private final SmsService smsService;

    private final UserRepository userRepository;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    public Map<String, Object> queryAll(ActivityUsersQueryCriteria criteria, Pageable pageable) {
        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        Page<ActivityUsers> page = activityUsersRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<ActivityUsersDto> map = page.map(activityUsersMapper::toDto);
        List<ActivityUsersDto> list = map.getContent();
        if (list != null) {
            for (ActivityUsersDto activityUsersDto : list) {
                Long userId = activityUsersDto.getUserId();
                if (userId != null) {
                    UserDto userDto = userService.findById(userId);
                    if (userDto != null) {
                        activityUsersDto.setUser(userDto);
                    }
                }
                Integer activityId = activityUsersDto.getActivityId();
                if (activityId != null) {
                    Optional<Activity> res = activityRepository.findById(activityId);
                    if (res.isPresent()) {
                        activityUsersDto.setActivity(res.get());
                    }
                }
                String chType = activityUsersDto.getChType();
                if (chType != null && chType.contains(";")) {
                    String[] res = chType.split(";");
                    activityUsersDto.setChTypes(res);
                }
            }
        }
        return PageUtil.toPage(map);
    }

    //根据不同设置不同的部门查看 处理  福建省;  或者  福建省;福州市;   或者 福建省;福州市;马尾区; 这种类型
    public String setCriteria(ActivityUsersQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            } else {
                return orgArea;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//包含福建省 则查全部
                return null;
            } else {
                if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                    //不赋予则返回所有都能看
                    return null;
                }
                if (res.getOrgArea().contains(";")) {
                    String[] split = res.getOrgArea().split(";");
                    if (split.length == 2) {
                        return split[1];
                    } else if (split.length == 3) {
                        return split[2];
                    } else if (split.length == 1) {
                        return split[0];
                    } else {
                        throw new BadRequestException("未符合规范的地区区域");
                    }
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            }
        } else {
            throw new BadRequestException("用户ID未找到");
        }
    }

    public List<ActivityUsersDto> queryAll(ActivityUsersQueryCriteria criteria) {
        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        return activityUsersMapper.toDto(activityUsersRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    public ActivityUsersDto findById(Integer userId) {
        ActivityUsers activityUsers = activityUsersRepository.findById(userId).orElseGet(ActivityUsers::new);
        ValidationUtil.isNull(activityUsers.getUserId(), "ActivityUsers", "userId", userId);
        return activityUsersMapper.toDto(activityUsers);
    }

    @Transactional(rollbackFor = Exception.class)
    public ActivityUsersDto create(ActivityUsersAddDto activityUsersAddDto) {
        Optional<Activity> res = activityRepository.findById(activityUsersAddDto.getActivityId());
        if (!res.isPresent()) {
            throw new BadRequestException("未找到活动");
        }
        ActivityUsers resources = new ActivityUsers();
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            resources.setUserId(userId);
        } catch (Exception e) {
        }
        resources.setActivityId(res.get().getId());
        resources.setAuditStatus(AUDIT_STATUS_BE_REVIEWED);
        resources.setPhone(activityUsersAddDto.getPhone());
        resources.setName(activityUsersAddDto.getName());
        resources.setOrgArea(res.get().orgArea);//活动的orgArea
        resources.setUnit(activityUsersAddDto.getUnit());
        Date date = new Date();
        Timestamp now = new Timestamp(date.getTime());
        resources.setSignTime(now);
        String[] chTypes = activityUsersAddDto.getChTypes();
        if (chTypes != null && chTypes.length > 0) {
            String last = "";
            for (String str : chTypes) {
                last = str + ";";
            }
            resources.setChType(last);
        }
        return activityUsersMapper.toDto(activityUsersRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(ActivityEditUsersDto activityEditUsersDto) {
        Optional<ActivityUsers> res = activityUsersRepository.findById(activityEditUsersDto.getId());
        if (!res.isPresent()) {
            throw new BadRequestException("未找到活动报名表id");
        }
        ActivityUsers activityUsers = res.get();
        activityUsers.setAuditStatus(activityEditUsersDto.getAuditStatus());
        ActivityUsers save = activityUsersRepository.save(activityUsers);
        if (save != null) {
            String auditStatus = save.getAuditStatus();
            Integer activityId = save.getActivityId();
            Optional<Activity> res2 = activityRepository.findById(activityId);
            String a = "";
            if (res2.isPresent()) {
                Activity activity = res2.get();
                a = activity.getTitle();
            }
            if (auditStatus != null && auditStatus.equals("审核通过")) {
                //发短信
                String[] phoneArray = new String[1];
                phoneArray[0] = save.getPhone();
                smsService.sendSuccessAddActivityMsg(phoneArray, a);
            }
        }
    }

    public void deleteAll(Integer[] ids) {
        for (Integer userId : ids) {
            activityUsersRepository.deleteById(userId);
        }
    }

    public void download(List<ActivityUsersDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ActivityUsersDto activityUsers : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("报名时间", activityUsers.getSignTime());
            map.put("审核状态", activityUsers.getAuditStatus());
            map.put("报名人员姓名", activityUsers.getName());
            map.put("所属单位/团队", activityUsers.getUnit());
            map.put("联系电话", activityUsers.getPhone());
            map.put("区域划分", activityUsers.getOrgArea());
            map.put("参会类型", activityUsers.getChType());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    public Map<String, Object> getMyActivity(ActivityUsersQueryCriteria criteria, Pageable pageable) {
        criteria.setUserId(SecurityUtils.getCurrentUserId());
        Page<ActivityUsers> page = activityUsersRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<ActivityUsersDto> map = page.map(activityUsersMapper::toDto);
        List<ActivityUsersDto> list = map.getContent();
        if (list != null) {
            for (ActivityUsersDto activityUsersDto : list) {
                Long userId = activityUsersDto.getUserId();
                if (userId != null) {
                    UserDto userDto = userService.findById(userId);
                    if (userDto != null) {
                        activityUsersDto.setUser(userDto);
                    }
                }
                Integer activityId = activityUsersDto.getActivityId();
                if (activityId != null) {
                    Optional<Activity> res = activityRepository.findById(activityId);
                    if (res.isPresent()) {
                        activityUsersDto.setActivity(res.get());
                    }
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public List<DictDetailDto> getActivityChType() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("activity_ch_type");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }
}